﻿using AutoMapper.Internal.Mappers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ERP.ERPSystem.ProductionSystem;
using ERP.ERPSystem.ProductionSystem.Dto;
using ERP.Team.ProductionSystem;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
using ERP.Team.RBAC;
using Volo.Abp.Domain.Repositories;

namespace ERP.Web.Controllers.ProductionSystem
{
    /// <summary>
    /// 生产系统-班组设置
    /// </summary>
    public class TeamSetController : Controller
    {
        private readonly ITeamSetServices _teamSetServices;
        private readonly IRepository<DepartmentModel, int> _departmentRepository;
        private readonly IRepository<UserModel, int> _userRepository;

        public TeamSetController(
            ITeamSetServices teamSetServices,
            IRepository<DepartmentModel, int> departmentRepository,
            IRepository<UserModel, int> userRepository)
        {
            _teamSetServices = teamSetServices;
            _departmentRepository = departmentRepository;
            _userRepository = userRepository;
        }

        /// <summary>
        /// 用于接收前端数据的简单DTO
        /// </summary>
        public class TeamUpdateDto
        {
            public int Id { get; set; }
            public string TeamNumber { get; set; }
            public string TeamName { get; set; }
            public string TeamType { get; set; }
        }

        /// <summary>
        /// 默认页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View("GetTeamSet");
        }

        /// <summary>
        /// 添加班组设置视图
        /// </summary>
        /// <returns></returns>
        public IActionResult AddTeam()
        {
            return View();
        }

        /// <summary>
        /// 编辑班组设置视图
        /// </summary>
        /// <param name="id">班组ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> EditTeam(int id)
        {
            try
            {
                if (id <= 0)
                {
                    return Json(new { success = false, message = "无效的班组ID" });
                }

                var team = await _teamSetServices.GetTeamById(id);
                if (team == null)
                {
                    return Json(new { success = false, message = "未找到指定的班组" });
                }

                return View(team);
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取班组数据失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取单个班组数据
        /// </summary>
        /// <param name="id">班组ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetTeamById(int id)
        {
            try
            {
                Console.WriteLine($"开始获取班组数据，ID: {id}");
                
                if (id <= 0)
                {
                    return Json(new { success = false, message = "无效的班组ID" });
                }

                var team = await _teamSetServices.GetTeamById(id);
                Console.WriteLine($"获取到的班组数据: {System.Text.Json.JsonSerializer.Serialize(team)}");
                
                if (team == null)
                {
                    return Json(new { success = false, message = "未找到指定的班组" });
                }

                return Json(new { success = true, data = team });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取班组数据时发生错误: {ex.Message}");
                return Json(new { success = false, message = $"获取数据失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 更新班组设置
        /// </summary>
        /// <param name="dto">更新数据</param>
        /// <returns></returns>
        [HttpPost]
        [Route("TeamSet/UpdateTeam")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UpdateTeam([FromBody] TeamUpdateDto dto)
        {
            try
            {
                Console.WriteLine($"UpdateTeam方法被调用");
                Console.WriteLine($"接收到的数据: {System.Text.Json.JsonSerializer.Serialize(dto)}");
                
                if (dto == null)
                {
                    Console.WriteLine("dto对象为null");
                    return Json(new { success = false, message = "无效的请求数据" });
                }

                if (dto.Id <= 0)
                {
                    Console.WriteLine($"dto.Id无效: {dto.Id}");
                    return Json(new { success = false, message = "无效的班组ID" });
                }

                // 先从数据库获取现有实体
                var existingTeam = await _teamSetServices.GetTeamById(dto.Id);
                if (existingTeam == null)
                {
                    Console.WriteLine($"未找到ID为{dto.Id}的班组");
                    return Json(new { success = false, message = "未找到指定的班组" });
                }

                // 更新属性值
                existingTeam.TeamNumber = dto.TeamNumber;
                existingTeam.TeamName = dto.TeamName;
                existingTeam.TeamType = dto.TeamType;

                Console.WriteLine($"准备更新班组，ID: {existingTeam.Id}, Name: {existingTeam.TeamName}, Type: {existingTeam.TeamType}");
                var result = await _teamSetServices.UpdateTeam(existingTeam);
                Console.WriteLine($"更新结果: {result}");
                
                return Json(new { success = result, message = result ? "更新成功" : "更新失败" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"UpdateTeam异常: {ex.Message}");
                Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                return Json(new { success = false, message = $"更新班组失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 生成班组编号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GenerateTeamNumber()
        {
            try
            {
                // 获取当前最大的班组编号
                var teams = await _teamSetServices.GetTeamSet();
                string teamNumber;

                if (!teams.Any())
                {
                    // 如果没有任何班组，从 "T0001" 开始
                    teamNumber = "T0001";
                }
                else
                {
                    // 获取最大的班组编号
                    var maxNumber = teams.Max(t => t.TeamNumber);
                    if (maxNumber != null && maxNumber.StartsWith("T") && maxNumber.Length == 5)
                    {
                        // 提取数字部分并增加1
                        if (int.TryParse(maxNumber.Substring(1), out int currentNumber))
                        {
                            teamNumber = $"T{(currentNumber + 1):D4}";
                        }
                        else
                        {
                            teamNumber = "T0001";
                        }
                    }
                    else
                    {
                        teamNumber = "T0001";
                    }
                }

                return Json(new { success = true, teamNumber = teamNumber });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"生成编号失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 生成编号 - 备用方法
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GenNumber()
        {
            try
            {
                var today = DateTime.Now.ToString("yyyyMMdd");
                var random = new Random().Next(100, 999);
                var teamNumber = $"T{today}{random}";
                return Json(new { success = true, teamNumber = teamNumber });
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = $"生成编号失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 保存班组设置 - 用于AJAX调用
        /// </summary>
        /// <param name="teamSetDto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("SaveTeam")]
        public async Task<JsonResult> SaveTeam([FromBody] TeamSetDto teamSetDto)
        {
            try
            {
                if (teamSetDto == null)
                {
                    return Json(new { success = false, message = "无效的请求数据" });
                }

                // 数据验证（如果是自动生成，允许编号为空或为AUTO_GENERATE）
                if (string.IsNullOrEmpty(teamSetDto.TeamNumber) && teamSetDto.TeamNumber != "AUTO_GENERATE")
                {
                    return Json(new { success = false, message = "班组编号不能为空" });
                }
                if (string.IsNullOrEmpty(teamSetDto.TeamName))
                {
                    return Json(new { success = false, message = "班组名称不能为空" });
                }
                if (string.IsNullOrEmpty(teamSetDto.TeamType))
                {
                    return Json(new { success = false, message = "班组分类不能为空" });
                }

                // 转换班组分类数字为文本
                switch (teamSetDto.TeamType)
                {
                    case "1":
                        teamSetDto.TeamType = "注塑";
                        break;
                    case "2":
                        teamSetDto.TeamType = "机加工";
                        break;
                    case "3":
                        teamSetDto.TeamType = "组装";
                        break;
                    case "4":
                        teamSetDto.TeamType = "仓库";
                        break;
                }

                var result = await _teamSetServices.AddTeams(teamSetDto);
                return Json(new { success = result > 0, message = result > 0 ? "保存成功" : "保存失败", data = result });
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = $"保存失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 添加班组设置 - 用于表单提交
        /// </summary>
        /// <param name="teamSetDto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("AddTeams")]
        public async Task<int> AddTeams(TeamSetDto teamSetDto)
        {
           var i=await _teamSetServices.AddTeams(teamSetDto);
            return i;
        }

        /// <summary>
        /// 显示班组设置视图
        /// </summary>
        /// <returns></returns>
        public IActionResult GetTeamSet()
        {
            return View();
        }

        /// <summary>
        /// 显示班组设置数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetTeamSets()
        {
            try
            {
                var teamlist = await _teamSetServices.GetTeamSet();
                return Json(teamlist);
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = $"获取数据失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取部门树形数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetDepartmentTree()
        {
            try
            {
                var departments = await _departmentRepository.GetListAsync();
                
                var treeData = departments.Select(dept => new
                {
                    id = dept.Id,
                    title = dept.DepartmentName,
                    spread = true // 默认展开
                }).ToList();

                return Json(new { success = true, data = treeData });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取部门数据失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取用户列表（支持分页和搜索）
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="limit">页大小</param>
        /// <param name="userName">用户名搜索</param>
        /// <param name="userPhone">电话搜索</param>
        /// <param name="departmentId">部门ID筛选</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserList(int page = 1, int limit = 10, string userName = "", string userPhone = "", int departmentId = 0)
        {
            try
            {
                var users = await GetUsersFromDatabase(userName, userPhone, departmentId, page, limit);
                var totalCount = await GetUserCountFromDatabase(userName, userPhone, departmentId);

                // 获取部门名称映射
                var departments = await _departmentRepository.GetListAsync();
                var departmentDict = departments.ToDictionary(d => d.Id, d => d.DepartmentName);

                var userData = users.Select(u => new
                {
                    userId = u.Id,
                    userName = u.UserName,
                    userNickName = u.UserNickName,
                    userPhone = u.UserPhone,
                    departmentName = departmentDict.ContainsKey(u.DepartmentId) ? departmentDict[u.DepartmentId] : "未知部门",
                    departmentId = u.DepartmentId
                }).ToList();

                return Json(new
                {
                    code = 0,
                    msg = "success",
                    count = totalCount,
                    data = userData
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    code = 1,
                    msg = $"获取用户数据失败: {ex.Message}",
                    count = 0,
                    data = new List<object>()
                });
            }
        }

        // 从数据库获取用户数据的方法
        private async Task<List<UserModel>> GetUsersFromDatabase(string userName, string userPhone, int departmentId, int page, int limit)
        {
            var queryable = await _userRepository.GetQueryableAsync();
            
            // 根据条件筛选
            if (!string.IsNullOrEmpty(userName))
            {
                queryable = queryable.Where(u => u.UserName.Contains(userName) || u.UserNickName.Contains(userName));
            }
            
            if (!string.IsNullOrEmpty(userPhone))
            {
                queryable = queryable.Where(u => u.UserPhone.Contains(userPhone));
            }
            
            if (departmentId > 0)
            {
                queryable = queryable.Where(u => u.DepartmentId == departmentId);
            }

            // 分页
            var users = queryable.Skip((page - 1) * limit).Take(limit).ToList();
            return users;
        }

        // 获取用户总数
        private async Task<int> GetUserCountFromDatabase(string userName, string userPhone, int departmentId)
        {
            var queryable = await _userRepository.GetQueryableAsync();
            
            // 根据条件筛选
            if (!string.IsNullOrEmpty(userName))
            {
                queryable = queryable.Where(u => u.UserName.Contains(userName) || u.UserNickName.Contains(userName));
            }
            
            if (!string.IsNullOrEmpty(userPhone))
            {
                queryable = queryable.Where(u => u.UserPhone.Contains(userPhone));
            }
            
            if (departmentId > 0)
            {
                queryable = queryable.Where(u => u.DepartmentId == departmentId);
            }

            return queryable.Count();
        }
        
        /// <summary>
        /// 删除班组设置
        /// </summary>
        /// <param name="id">班组ID</param>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        [Route("TeamSet/DeleteTeamSet")]
        [IgnoreAntiforgeryToken]
        public async Task<IActionResult> DeleteTeamSet(int id)
        {
            try
            {
                Console.WriteLine($"DeleteTeamSet方法被调用，ID: {id}");
                
                if (id <= 0)
                {
                    return Json(new { success = false, message = "无效的班组ID" });
                }

                // 检查班组是否存在
                var existingTeam = await _teamSetServices.GetTeamById(id);
                if (existingTeam == null)
                {
                    return Json(new { success = false, message = "班组不存在" });
                }

                Console.WriteLine($"准备删除班组: ID={id}, Name={existingTeam.TeamName}");
                
                // 调用服务层删除方法
                var result = await _teamSetServices.DeleteTeamSetAsync(id);
                
                Console.WriteLine($"删除结果: Success={result.IsSuccess}, Message={result.Message}");
                
                if (result.IsSuccess)
                {
                    return Json(new { success = true, message = result.Message });
                }
                else
                {
                    return Json(new { success = false, message = result.Message });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除班组异常: {ex.Message}");
                Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                return Json(new { success = false, message = $"删除失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 简化的删除班组方法
        /// </summary>
        /// <param name="id">班组ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Delete(int id)
        {
            try
            {
                Console.WriteLine($"Delete方法被调用，ID: {id}");
                
                if (id <= 0)
                {
                    return Json(new { success = false, message = "无效的班组ID" });
                }

                // 检查班组是否存在
                var existingTeam = await _teamSetServices.GetTeamById(id);
                if (existingTeam == null)
                {
                    return Json(new { success = false, message = "班组不存在" });
                }

                Console.WriteLine($"准备删除班组: ID={id}, Name={existingTeam.TeamName}");
                
                // 调用服务层删除方法
                var result = await _teamSetServices.DeleteTeamSetAsync(id);
                
                Console.WriteLine($"删除结果: Success={result.IsSuccess}, Message={result.Message}");
                
                return Json(new { 
                    success = result.IsSuccess, 
                    message = result.Message 
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除班组异常: {ex.Message}");
                return Json(new { success = false, message = $"删除失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取班组成员列表
        /// </summary>
        /// <param name="teamId">班组ID</param>
        /// <param name="page">页码</param>
        /// <param name="limit">每页数量</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetTeamMembers(int teamId, int page = 1, int limit = 10)
        {
            try
            {
                // 获取班组信息
                var team = await _teamSetServices.GetTeamById(teamId);
                if (team == null)
                {
                    return Json(new { success = false, message = "班组不存在" });
                }

                // 获取用户列表（这里使用模拟数据，实际应该从数据库获取）
                var users = new List<object>
                {
                    new { userName = "test", userNickName = "测试员", userPhone = "13800138000" },
                    new { userName = "kf1", userNickName = "张作霖", userPhone = "16666666666" }
                };

                return Json(new
                {
                    success = true,
                    data = users,
                    total = users.Count,
                    message = "获取成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取班组成员失败：{ex.Message}" });
            }
        }
    }
}
